<template>
  <s-layout title="鲸囍云店">
    <view class="rank-container" :style="{top: sheep.$platform.device.statusBarHeight + 44 + 'px'}">
      <!-- <su-sticky bgColor="#fff"> -->
      <view class="tab-cons">
        <su-tabs 
          :list="tabMaps" 
          lineColor="#3662EC" 
          :activeStyle="{ color: '#3662EC' }" 
          :scrollable="false"
          :current="state.currentTab" @change="onTabsChange">
        </su-tabs>
      </view>
      <!-- </su-sticky> -->

      <!-- <view class="top123">
        <view class="item" :class="{'top1': item.rank == 2, 'top2': item.rank == 1, 'top3': item.rank == 3}" v-for="(item, index) in state.rankTOPList" :key="item.nickname">
          
          <view class="star">
            <image :src="starEnum[index]" mode="widthFix"></image>
          </view>
          <view class="avatar">
            <image :src="sheep.$url.cdn(item.avatar)" mode=""></image>
          </view>
          <view class="name">{{ item.nickname }}</view>
          <view class="type">
            <image :src="shopTypEnum[state.grade] || shopTypEnum['gold']" mode="aspectFill"></image>
          </view>
          <view class="sales">销量：{{ item.order_num }}</view>
        </view>
      </view> -->


      <view class="top123">
        <view class="item top2">
          <view class="star">
            <image :src="starEnum[0]" mode="widthFix"></image>
          </view>
          <view class="avatar">
            <image :src="sheep.$url.cdn(state.top2Data?.avatar)" mode=""></image>
          </view>
          <view class="name">{{ state.top2Data?.nickname || '--' }}</view>
          <view class="type">
            <image :src="shopTypEnum[state.grade] || shopTypEnum['gold']" mode="aspectFill"></image>
          </view>
          <view class="sales">销量：{{ state.top2Data?.order_num }}</view>
        </view>
        <view class="item top1">
          <view class="star">
            <image :src="starEnum[1]" mode="widthFix"></image>
          </view>
          <view class="avatar">
            <image :src="sheep.$url.cdn(state.top1Data?.avatar)" mode=""></image>
          </view>
          <view class="name">{{ state.top1Data?.nickname || '--' }}</view>
          <view class="type">
            <image :src="shopTypEnum[state.grade] || shopTypEnum['gold']" mode="aspectFill"></image>
          </view>
          <view class="sales">销量：{{ state.top1Data?.order_num }}</view>
        </view>
        <view class="item top3">
          <view class="star">
            <image :src="starEnum[2]" mode="widthFix"></image>
          </view>
          <view class="avatar">
            <image :src="sheep.$url.cdn(state.top3Data?.avatar)" mode=""></image>
          </view>
          <view class="name">{{ state.top3Data?.nickname || '--' }}</view>
          <view class="type">
            <image :src="shopTypEnum[state.grade] || shopTypEnum['gold']" mode="aspectFill"></image>
          </view>
          <view class="sales">销量：{{ state.top3Data?.order_num }}</view>
        </view>
      </view>
      
 

      <view class="rank" :style="{ height: state.listHeight + 'px' }">
        <scroll-view scroll-y 
          class="scroll-view"
          :show-scrollbar="false"
          :enhanced="true"
          :bounces="true">
          <!-- 列表内容 -->
          <view v-if="state.rankList.length > 0" class="list-item" v-for="item in state.rankList" :key="item.rank">
            <!-- 排名 -->
            <view class="rank-num">{{item.rank}}</view>
            
            <!-- 用户信息 -->
            <view class="avatar">
              <image :src="sheep.$url.cdn(item.avatar)" mode="aspectFill"></image>
            </view>

            <view class="name">
              <view class="name-text ss-line-1">{{item.nickname}}</view>
              <view class="type">
                <image :src="shopTypEnum[state.grade] || shopTypEnum['gold']" mode="widthFix"></image>
              </view>
            </view>
            
            <!-- 销量 -->
            <view class="sales">
              <view class="text">{{item.order_num}}</view>
              <view class="num">销售</view>
            </view>
          </view>
          <!-- 暂无数据 -->
          <s-empty v-else paddingTop="20" 
            icon="https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/mengchong/soldout-empty.png" text="暂无数据">
          </s-empty>
        </scroll-view>
      </view>
    </view>

    <!-- 加号 -->
    <view class="fab-container">
      <!-- 主按钮 -->
      <view 
        class="fab-button" 
        :class="{'fab-button--active': state.isActive}"
        @tap="toggleMenu"
      >
        <image :src="sheep.$url.cdn('/storage/default/20250427/ff430cf06ab3f21372182546b0b1da7e.png')" mode="widthFix"></image>
      </view>
      
      <!-- 子按钮容器 -->
      <view class="fab-menu" :class="{'fab-menu--active': state.isActive}">
        <view 
          v-for="(item, index) in menuItems" 
          :key="index"
          class="fab-menu__item"
          @click="onMenuClick(item)"
          :style="{
            transitionDelay: state.isActive ? `${index * 0.05}s` : '0s'
          }"
        >
          <image :src="item.icon" class="fab-menu__item-image" mode="aspectFill" />
        </view>
      </view>
    </view>
  </s-layout>
</template>

<script setup>
import { computed, reactive, ref, onMounted } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app';
import sheep from '@/sheep';
console.log(sheep.$platform.device.statusBarHeight, 'sheep.$platform.device.statusBarHeight')
import { isEmpty } from 'lodash';
const tabMaps = [
  {
    name: '今日',
    value: '1',
  },
  {
    name: '本周',
    value: '2',
  },
  {
    name: '本月',
    value: '3',
  },
  {
    name: '全部',
    value: '4',
  },
];

const footerTbs = [
  {
    name: '云店数据',
    value: 'all',
    icon: '/storage/default/20250425/00d96c1d1571396b8746254ecf9949b6.png',
  },
  {
    name: '我的团队',
    value: 'yes',
    icon: '/storage/default/20250425/f08f4d43792a8116ac46445c0ccacd85.png',
  },
  {
    name: '我的云店',
    value: 'back',
    icon: '/storage/default/20250425/66d0e0463301707f0701fe2ebe470c5a.png',
  }
];

const menuItems = [
  {
    icon: 'https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/storage/default/20250427/5fc10f52b5499a5cf370bef8e41a95da.png',
    grade: ''
  },
  {
    icon: 'https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/storage/default/20250427/4d8a27f443a1041c17b4fde2a0e8109f.png',
    grade: 'honor'
  },
  {
    icon: 'https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/storage/default/20250427/7ff0f2f1fc8874f6159fb5afa3e306ed.png',
    grade: 'starshine'
  },
  {
    icon: 'https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/storage/default/20250427/5e21326d16855ea3ac09bdaef4457083.png',
    grade: 'diamond'
  },
  {
    icon: 'https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/storage/default/20250427/396f5b580efa51f358987263caff73b1.png',
    grade: 'gold'
  },
];
// 店铺类型
const shopTypEnum = {
  'gold': 'https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/storage/default/20250427/f1eab700a52dd9258a8c17b86b74b7b3.png',
  'diamond': 'https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/storage/default/20250427/1d0a807a8a9eb7690ed9725f903d1a94.png',
  'starshine': 'https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/storage/default/20250427/8d00bf6ec97fc3d6bbd90c9644223732.png',
  'honor': 'https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/storage/default/20250427/31d60cdf2fe41a79a3ec5e9e7a564c40.png',
}

// 皇冠 
const starEnum = {
  0: 'https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/storage/default/20250427/e6c9b679a33de726b4bc24dc94e472c2.png',
  1: 'https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/storage/default/20250427/8dd375a07beb84f43bab80e1a84c7916.png',
  2: 'https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/storage/default/20250427/c17ec5a6575eaa4f73890072a331c447.png',
}


const onMenuClick = (item) => {
  if (item.grade == '') {
    sheep.$router.go('/pages/commission/merchant/incomePage')
  } else {
    state.grade = item.grade
    getRankList()
  }
  state.isActive = false
}

const state = reactive({
  currentTab: 0, 
  type: '1', // 1=今天 2=本周 3=本月 4=全部
  grade: 'gold', // gold=黄金,diamond=钻石,starshine=星耀,honor=荣耀
  currentFooterTab: 0,
  top1Data: {},
  top2Data: {},
  top3Data: {},

  rankTOPList: [
    // {
    //   rank: 'TOP 2',
    //   avatar: '/storage/default/20250424/1976367572fbb88a678f18c19c2f2a63.jpg',
    //   nickname: '张三',
    //   order_num: '1000',
    // },
    // {
    //   rank: 'TOP 1',
    //   avatar: '/storage/default/20250424/1976367572fbb88a678f18c19c2f2a63.jpg',
    //   nickname: '李四',
    //   order_num: '1000',
    // },
    // {
    //   rank: 'TOP 3',
    //   avatar: '/storage/default/20250424/1976367572fbb88a678f18c19c2f2a63.jpg',
    //   nickname: '王五',
    //   order_num: '1000',
    // }
  ],
  rankList: [
    // {
    //   rank: 1,
    //   avatar: '/storage/default/20250424/1976367572fbb88a678f18c19c2f2a63.jpg',
    //   nickname: '张三',
    //   order_num: '2',
    // },
  ],
  isActive: false,
  listHeight: 0,
})

const calculateRankHeight = () => {
  const systemInfo = uni.getSystemInfoSync();
  const windowHeight = systemInfo.windowHeight;
  const stickyHeight = 44 + 162; // su-sticky的固定高度
  console.log(windowHeight, 'windowHeight')
  state.listHeight = windowHeight - stickyHeight - 184;
  console.log(state.listHeight, 'state.listHeight')
};


onMounted(() => {
  setTimeout(() => {
    calculateRankHeight();
  }, 100);
});

const toggleMenu = () => {
  state.isActive = !state.isActive
}

const getItemPosition = (index) => {
  const menuItems = document.querySelectorAll('.fab-menu__item')
  const menuItem = menuItems[index]
  const { top, left } = menuItem.getBoundingClientRect()
  return `translate(${left}px, ${top}px)`
}




const getRankList = async () => {
  try {
    const { error, data } = await sheep.$api.store.getCyqRankListNew({ type: state.type, grade: state.grade });
    if (error === 0) {
      state.top1Data = {}
      state.top2Data = {}
      state.top3Data = {}
      state.rankList = []
      // 默认空对象模板
      const defaultItem = {
        nickname: '--',
        avatar: '',
        order_num: '0',
        grade: 'gold'
      };

      // 如果数据正好3个
      if (data.length === 3) {
        console.log(state.top1Data, state.top2Data,state.top3Data, '数据=3个')
        // state.rankTOPList = [
        //   { ...data[1], rank: 1 }, // 第二个放第一位
        //   { ...data[0], rank: 2 }, // 第一个放第二位
        //   { ...data[2], rank: 3 }  // 第三个保持不变
        // ];
        state.top1Data = data[0]
        state.top2Data = data[1]
        state.top3Data = data[2]

        state.rankList = [];
      } else if (data.length < 3) { // 如果数据小于3个
        console.log(data)
        console.log(data.length, '如果数据小于3个')

        if (data.length == 0) {
          state.top1Data = defaultItem
          state.top2Data = defaultItem
          state.top3Data = defaultItem
          console.log(state.top1Data, state.top2Data,state.top3Data, '数据=0个')
        } else if (data.length == 1) {
          state.top1Data = data[0]
          state.top2Data = defaultItem
          state.top3Data = defaultItem
          console.log(state.top1Data, state.top2Data,state.top3Data, '数据=1个')
        } else if (data.length == 2) {
          state.top1Data = data[0]
          state.top2Data = data[1]
          state.top3Data = defaultItem
          console.log(state.top1Data, state.top2Data,state.top3Data, '数据=2个')
        } 
        state.rankList = [];
      } else { // 如果数据大于3个
        // 取前3个作为TOP3
        console.log(data, 'data 大于3个数据')
        state.top1Data = data[0]
        state.top2Data = data[1]
        state.top3Data = data[2]

        // 剩余的放入rankList并重新计算rank
        state.rankList = data.slice(3).map((item, index) => ({
          ...item,
          rank: index + 4
        }));
      }
    } else {
      uni.$toast.error(data?.message || '获取数据失败');
    }
  } catch (err) {
    console.error('获取排名列表失败:', err);
    uni.$toast.error('获取数据失败');
  }
};

function onTabsChange(e) {
  console.log(e, 'onTabsChange=')
  state.currentTab = e.index;
  state.type = tabMaps[e.index].value;
  getRankList()
}

const onFooterTabClick = async (index) => {
  console.log(index, 'onFooterTabClick=')
  if (index == 1) {
    uni.navigateTo({
      url: '/pages/store/team'
    })
  } else if (index == 2) {
    try {
      const { error, data } = await sheep.$api.store.getOwnStoreInfo()
      console.log(error, 'error====shop');
      console.log(data, 'res');
     
      if (JSON.parse(uni.getStorageSync('user-store')).userInfo.id == null) {
        return
      } else {
        uni.setStorageSync('shopInfo', JSON.stringify(data))
        uni.navigateTo({
          url: '/pages/store/shop?id=' + data.id
        })
      }
    } catch(err) {
      uni.$toast.error('获取数据失败');
    }
  }
}

onLoad(() => {
  getRankList();
});

</script>

<style lang="scss" scoped>
@import './style/rank.scss';
</style>
